//
//  HomeQuickCheckVC.m
//  Ginix
//
//  Created by fzq on 2025/2/24.
//

#import "HomeQuickCheckVC.h"
#import "HomeCheckBar.h"
#import "HealthQuickInfoVC.h"

@interface HomeQuickCheckVC ()
@property (nonatomic,strong) UIImageView * backView;
@property (nonatomic,strong) UILabel * infoLabel;
@property (nonatomic,strong) UIButton * enterBtn;
@property (nonatomic,strong) UIImageView * iconView;
@property (nonatomic,strong) UILabel * tipsLabel;
@property (nonatomic,strong) HomeCheckBar * checkBar;
@property (nonatomic,strong) HomeTipsView * tipsView;

@property (nonatomic,assign) NSInteger q2;
@property (nonatomic,assign) NSInteger heart;
@property (nonatomic,assign) NSInteger heartRota;
@property (nonatomic,assign) CGFloat  temp;
@end

@implementation HomeQuickCheckVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubViewLayout];
}
-(void)setSubViewLayout{
    
    self.title = @"快速检测";
    self.navgationView.infoLabel.textColor = RDRGB(0x714933);
    
    [self.view addSubview:self.backView];
    [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.infoLabel];
    [self.view addSubview:self.iconView];
    [self.view addSubview:self.checkBar];
    [self.view addSubview:self.tipsLabel];
    
    [self.view addSubview:self.enterBtn];
    [_enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(330 * FMScaleX, 50 * FMScaleX));
        make.centerX.equalTo(@0);
        make.bottom.mas_offset(-kSafeAreaHeight - 50 * FMScaleX);
    }];
    
    [self.view bringSubviewToFront:self.navgationView];
    [(BaseNavController *)[UIViewController findNavigationController]addFullScreenPopBlackListItem:self];

}

-(void)backBtnClick{
    [super backBtnClick];
    
    NSLog(@"222");
    
}
 
-(void)enterBtnAction{
    [[BCLRingManager shared] getBlcConnectWithCompletion:^(BOOL state) {
        if (!state) {
            FhudShowStr(@"设备未连接");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                id vc = [[NSClassFromString(@"HomeJoinVC") alloc]init];
                [[UIViewController findNavigationController] pushViewController:vc
                                                                       animated:YES];
            });
        }else{
            self.tipsLabel.text = @"请保持戒指在左手手指不要取下...";
            self.enterBtn.enabled = NO;
            self.enterBtn.alpha = 0.8;
            @WeakObj(self)
            [self requestHeart:^( NSInteger value) {
                @StrongObj(self)
                self.heart = value;
                    [self requestHrv:^( NSInteger value) {
                        @StrongObj(self)
                        self.heartRota = value;
                            [self requestOxy:^( NSInteger value) {
                                @StrongObj(self)
                                self.q2 = value;
                                    [self requestBody:^( float value) {
                                        @StrongObj(self)
                                        self.temp = value;
                                        [self updateQuickCheckData];
                                    }];
                            }];
                    }];
            }];
        }
    }];
}

-(void)reloadFirstCheckType{
    
    self.enterBtn.enabled = YES;
    self.enterBtn.alpha = 1;
    [self updateTotalProgressWithMethodIndex:1 andProgress:0];
    [self.enterBtn setTitle:@"开始检测" forState:UIControlStateNormal];
    
}

-(void)requestHeart:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startHeartRateMeasurementWithRrTime:20 progress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:1 andProgress:progress * 100];
    } rrData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
        
    } heartRate:^(NSInteger value) {
        
    } completion:^(BOOL success, NSInteger value) {
        if (!success) {
            FhudShowStr(@"心率检测失败，请佩戴好戒指之后重新检测")
            [self reloadFirstCheckType];

        }else{
            !respone?:respone(value);
        }
    }];
}
-(void)requestHrv:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startHRVMeasurementWithProgress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:2 andProgress:progress * 100];
        } waveData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
            
        } completion:^(BOOL success, NSInteger value) {
            if (!success) {
                FhudShowStr(@"HRV检测失败，请佩戴好戒指之后重新检测")
                [self reloadFirstCheckType];
                
            }else{
                !respone?:respone(value);
            }
        }];
}


-(void)requestOxy:(void(^)(NSInteger value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] startO2MeasurementWithProgress:^(double progress) {
        @StrongObj(self)
        [self updateTotalProgressWithMethodIndex:3 andProgress:progress * 100];

        } waveData:^(NSInteger sequence, NSInteger count, NSArray<NSNumber *> * _Nonnull data) {
            
        } completion:^(BOOL success, NSInteger value) {
            if (!success) {
                FhudShowStr(@"血氧测量失败，请佩戴好戒指之后重新检测")
                [self reloadFirstCheckType];
            }else{
                !respone?:respone(value);
            }
        }];
}


-(void)requestBody:(void(^)(float value))respone{
    @WeakObj(self)
    [[BCLRingManager shared] readTemperatureWithCompletion:^(BOOL success, float temperature) {
        @StrongObj(self)
        if (success) {
            [self updateTotalProgressWithMethodIndex:4 andProgress:1];
            !respone?:respone(temperature);
        }else{
            FhudShowStr(@"体温测量失败，请佩戴好戒指之后重新检测")
            [self reloadFirstCheckType];
        }
    }];
}

- (void)updateTotalProgressWithMethodIndex:(NSInteger)index andProgress:(float)progress {
    float singleMethodProgress = progress / 4.0;
    float totalProgress = 0.0;
    switch (index) {
        case 1:
            totalProgress = singleMethodProgress;
            break;
        case 2:
            totalProgress = 25 + singleMethodProgress;
            break;
        case 3:
            totalProgress = 50 + singleMethodProgress;
            break;
        case 4:
            totalProgress = 100;
            break;
        default:
            break;
    }
    self.checkBar.progress = totalProgress;
}

-(void)updateQuickCheckData{
    
    
    NSDictionary * parm = @{@"heart":@(self.heart),@"heartRota":@(self.heartRota),@"q2":@(self.q2),@"temp":@(self.temp)};
    [SPNetworkingIns POST:PORT(@"bh-center/api/invite/QuickTesting") params:parm success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {        
        HomeQuickCheckModel * model = [HomeQuickCheckModel yy_modelWithDictionary:responseObject[@"data"]];
        HealthQuickInfoVC * vc = [[HealthQuickInfoVC alloc]init];
        vc.ID = model.ID;
        [self.navigationController pushViewController:vc animated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:RefshQuickDataNotification object:nil];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

-(UILabel *)infoLabel{
    
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH - 320 * FMScaleX) / 2, NavHeight + 20 * FMScaleX, 320 * FMScaleX, 40 * FMScaleX)];
        _infoLabel.font = Regular(14);
        _infoLabel.textColor = RDRGB(0x714933);
        _infoLabel.numberOfLines = 0;
        _infoLabel.text = @"快速健康检测开始时，请确保您的戒指佩戴在手指上。";
    }
    return _infoLabel;
}
-(UIButton *)enterBtn{
    
    if (!_enterBtn) {
        _enterBtn = [[UIButton alloc]init];
        [_enterBtn setBackgroundImage:[UIImage imageNamed:@"Common_btn_bg"] forState:UIControlStateNormal];
        [_enterBtn setTitle:@"开始检测" forState:UIControlStateNormal];
        [_enterBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_enterBtn addTarget:self action:@selector(enterBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _enterBtn;
}
-(UIImageView *)iconView{
    
    
    if(!_iconView){
        _iconView = [[UIImageView alloc]initWithFrame:CGRectMake(20 * FMScaleX, GETMaxY(self.infoLabel) + 15 * FMScaleX, 80 * FMScaleX, 80 * FMScaleX)];
        _iconView.image = [UIImage imageNamed:@"Home_quick_icon"];
    }
    return _iconView;
}
-(UIImageView *)backView{
    
    if(!_backView){
        _backView = [[UIImageView alloc]init];
        _backView.image = [UIImage imageNamed:@"Home_quick_bg"];
    }
    return _backView;
}

-(HomeCheckBar *)checkBar{

    if(!_checkBar){
        _checkBar = [[HomeCheckBar alloc]initWithFrame:CGRectMake(GETMaxX(self.iconView) + 20 * FMScaleX, GETMaxY(self.infoLabel) + 26 * FMScaleX, 234 * FMScaleX, 40 * FMScaleX)];
    }
    return _checkBar;
}

-(UILabel *)tipsLabel{
    
    if (!_tipsLabel) {
        _tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(GETMinX(self.checkBar), GETMaxY(self.checkBar) + 6 * FMScaleX, 200 * FMScaleX, 20 * FMScaleX)];
        _tipsLabel.font = Regular(13 * FMScaleX);
        _tipsLabel.textColor = RDRGB(0xAD7D62);
        _tipsLabel.text = @"请将戒指佩戴在左手手指上";
    }
    return _tipsLabel;
}

-(HomeTipsView *)tipsView{
    
    if (!_tipsView) {
        _tipsView = [[HomeTipsView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_tipsView];
    }
    return _tipsView;
}
@end
